//
// Created by Cammy on 2024/4/26.
//

#include "Stack.h"

void StackInit(Stack *ps) {
    ps->arr = (STDataType *) malloc(sizeof(STDataType) * 4);
    if (ps->arr == NULL) {
        printf("malloc fail...\n");
        exit(-1);
    }
    ps->capacity = 4;
//    ps->top = -1; // 意味着top指向栈顶元素
    ps->top = 0; // 意味着top指向的是栈顶元素的下一个
}

void StackDestroy(Stack *ps) {
    assert(ps);
    free(ps->arr);
    ps->arr = NULL;
    ps->top = ps->capacity = 0;
}

void BuyCapacity(Stack *ps) {
    STDataType *tmp = realloc(ps->arr, ps->capacity * 2 * sizeof(STDataType));
    if (tmp == NULL) {
        printf("realloc fail...\n");
        exit(-1);
    }

    ps->arr = tmp;
    ps->capacity *= 2;
}

// 压栈
void StackPush(Stack *ps, STDataType x) {
    assert(ps);

    // 满了就增容
    if (ps->top == ps->capacity) {
        BuyCapacity(ps);
    }

    ps->arr[ps->top] = x;
    ps->top++;

}

// 出栈
void StackPop(Stack *ps) {
    assert(ps);
    // 栈空了调用Pop直接报错终止
    assert(ps->top > 0);

    ps->top--;
}

STDataType StackTop(Stack *ps) {
    assert(ps);
    // 栈空了调用Top直接报错终止
    assert(ps->top > 0);

    return ps->arr[ps->top - 1];
}

int StackSize(Stack *ps) {
    assert(ps);

    return ps->top;
}

bool StackEmpty(Stack *ps) {
    assert(ps);

    return ps->top == 0;
}